package com.winit.commons.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.List;

/**
 * Created by wangjian on 16/1/15.
 * <p>
 * 操作json配置文件工具类,包括读取/保存,返回bean
 */
public class JSONFileUtil {

    static final Logger log = LoggerFactory.getLogger(JSONFileUtil.class);

    /**
     * 读取json文件,并转换成javabean
     *
     * @param filePath
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getFileJsonForBean(String filePath, Class<T> clazz) {
        T t = null;
        String str = getFileString(filePath);
        if (!StringUtils.isEmpty(str)) {
            t = JSONObject.parseObject(str.toString(), clazz);
        }
        return t;
    }

    public static <T> List<T> getFileJsonForList(String filePath, Class<T> clazz) {
        List<T> t = null;
        String str = getFileString(filePath);
        if (!StringUtils.isEmpty(str)) {
            t = JSONArray.parseArray(str.toString(), clazz);
        }
        return t;
    }


    /**
     * 保存json文件
     *
     * @param filePath
     * @param t
     * @return
     */
    public static <T> boolean saveFileJson(String filePath, T t) {
        boolean flag = false;
        String str = JSONObject.toJSONString(t, true);
        FileWriter fw = null;
        PrintWriter out = null;
        try {
            fw = new FileWriter(filePath);
            out = new PrintWriter(fw);
            out.write(str);
            out.println();
            fw.close();
            out.close();
            flag = true;
        } catch (IOException e) {
            log.error("保存json文件异常,e:" + e.getMessage());
        } finally {
            try {
                fw.close();
                out.close();
            } catch (IOException e) {
                log.error("保存json文件异常,e:" + e.getMessage());
            }
        }
        return flag;
    }

    public static boolean saveFile(String filePath,String text) {
        log.info("修改文件,path="+filePath);
        boolean flag = false;
        String lineSeparator = System.getProperty("line.separator");
        String[] texts = text.split(lineSeparator);
        FileWriter fw = null;
        PrintWriter out = null;
        try {
            fw = new FileWriter(filePath);
            out = new PrintWriter(fw);
            for (String str : texts){
                out.write(str);
                out.write(lineSeparator);
            }
            fw.close();
            out.close();
            flag = true;
        } catch (IOException e) {
            log.error("保存文件异常,e:" + e.getMessage());
        } finally {
            try {
                fw.close();
                out.close();
            } catch (IOException e) {
                log.error("保存文件异常,e:" + e.getMessage());
            }
        }
        return flag;
    }

    /**
     * 从文件中读取信息,拼接成一个字符串返回.
     *
     * warning!不适合对应大文件.
     *
     * @param filePath
     * @param hasLineSeparator
     * @return
     */
    public static String getFileString(String filePath, boolean hasLineSeparator) {
        BufferedReader reader = null;
        StringBuffer str = new StringBuffer();

        String lineSeparator = System.getProperty("line.separator");
        FileInputStream fileInputStream = null;
        InputStreamReader inputStreamReader = null;
        try {
            fileInputStream = new FileInputStream(filePath);
            inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
            reader = new BufferedReader(inputStreamReader);
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                str.append(tempString);

                //如果需要换行符,在这里补充.
                if (hasLineSeparator) {
                    str.append(lineSeparator);
                }
            }
        } catch (Exception e) {
            log.error("读取json文件异常,e:" + e.getMessage());
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
                if(inputStreamReader != null){
                    inputStreamReader.close();
                }
                if(fileInputStream != null){
                    fileInputStream.close();
                }

            } catch (Exception e) {
                log.error("读取json文件,关闭流异常,e:" + e.getMessage());
            }

        }
        return str.toString();
    }

    public static String getFileString(String filePath) {
       return getFileString(filePath,false);
    }
}

